// 代码图谱视图组件
import React, { useState, useEffect, useRef } from 'react';
import { invoke } from '@tauri-apps/api/core';

interface GraphViewProps {
  className?: string;
}

interface GraphNode {
  id: string;
  label: string;
  type: 'file' | 'function' | 'class' | 'variable';
  size: number;
  color: string;
}

interface GraphEdge {
  id: string;
  source: string;
  target: string;
  type: 'imports' | 'calls' | 'extends' | 'implements';
  weight: number;
}

interface GraphData {
  nodes: GraphNode[];
  edges: GraphEdge[];
}

export const GraphView: React.FC<GraphViewProps> = ({ className }) => {
  const [graphData, setGraphData] = useState<GraphData | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [selectedNode, setSelectedNode] = useState<GraphNode | null>(null);
  const [viewMode, setViewMode] = useState<'overview' | 'detailed'>('overview');
  const canvasRef = useRef<HTMLCanvasElement>(null);

  // 加载图谱数据
  const loadGraphData = async () => {
    setIsLoading(true);
    try {
      const response = await invoke('get_code_graph') as any;
      if (response.success) {
        setGraphData(response.data);
      }
    } catch (error) {
      console.error('Failed to load graph data:', error);
      // 设置模拟数据
      setGraphData({
        nodes: [
          {
            id: 'app',
            label: 'App.tsx',
            type: 'file',
            size: 20,
            color: '#3b82f6'
          },
          {
            id: 'router',
            label: 'Router.tsx',
            type: 'file',
            size: 15,
            color: '#3b82f6'
          },
          {
            id: 'store',
            label: 'Store.ts',
            type: 'file',
            size: 18,
            color: '#10b981'
          },
          {
            id: 'component1',
            label: 'Component1',
            type: 'class',
            size: 12,
            color: '#f59e0b'
          },
          {
            id: 'function1',
            label: 'handleClick',
            type: 'function',
            size: 8,
            color: '#ef4444'
          }
        ],
        edges: [
          {
            id: 'e1',
            source: 'app',
            target: 'router',
            type: 'imports',
            weight: 1
          },
          {
            id: 'e2',
            source: 'app',
            target: 'store',
            type: 'imports',
            weight: 1
          },
          {
            id: 'e3',
            source: 'router',
            target: 'component1',
            type: 'imports',
            weight: 1
          },
          {
            id: 'e4',
            source: 'component1',
            target: 'function1',
            type: 'calls',
            weight: 2
          }
        ]
      });
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    loadGraphData();
  }, []);

  // 简单的图谱渲染
  useEffect(() => {
    if (!graphData || !canvasRef.current) return;

    const canvas = canvasRef.current;
    const ctx = canvas.getContext('2d');
    if (!ctx) return;

    // 清空画布
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    const centerX = canvas.width / 2;
    const centerY = canvas.height / 2;
    const radius = 150;

    // 绘制边
    graphData.edges.forEach((edge, index) => {
      const sourceNode = graphData.nodes.find(n => n.id === edge.source);
      const targetNode = graphData.nodes.find(n => n.id === edge.target);
      
      if (sourceNode && targetNode) {
        const sourceIndex = graphData.nodes.indexOf(sourceNode);
        const targetIndex = graphData.nodes.indexOf(targetNode);
        
        const sourceAngle = (sourceIndex / graphData.nodes.length) * 2 * Math.PI;
        const targetAngle = (targetIndex / graphData.nodes.length) * 2 * Math.PI;
        
        const sourceX = centerX + Math.cos(sourceAngle) * radius;
        const sourceY = centerY + Math.sin(sourceAngle) * radius;
        const targetX = centerX + Math.cos(targetAngle) * radius;
        const targetY = centerY + Math.sin(targetAngle) * radius;

        ctx.beginPath();
        ctx.moveTo(sourceX, sourceY);
        ctx.lineTo(targetX, targetY);
        ctx.strokeStyle = '#6b7280';
        ctx.lineWidth = edge.weight;
        ctx.stroke();
      }
    });

    // 绘制节点
    graphData.nodes.forEach((node, index) => {
      const angle = (index / graphData.nodes.length) * 2 * Math.PI;
      const x = centerX + Math.cos(angle) * radius;
      const y = centerY + Math.sin(angle) * radius;

      // 绘制节点圆圈
      ctx.beginPath();
      ctx.arc(x, y, node.size, 0, 2 * Math.PI);
      ctx.fillStyle = node.color;
      ctx.fill();
      ctx.strokeStyle = selectedNode?.id === node.id ? '#000' : '#fff';
      ctx.lineWidth = selectedNode?.id === node.id ? 3 : 1;
      ctx.stroke();

      // 绘制标签
      ctx.fillStyle = '#000';
      ctx.font = '12px Arial';
      ctx.textAlign = 'center';
      ctx.fillText(node.label, x, y + node.size + 15);
    });
  }, [graphData, selectedNode]);

  // 处理画布点击
  const handleCanvasClick = (event: React.MouseEvent<HTMLCanvasElement>) => {
    if (!graphData || !canvasRef.current) return;

    const canvas = canvasRef.current;
    const rect = canvas.getBoundingClientRect();
    const x = event.clientX - rect.left;
    const y = event.clientY - rect.top;

    const centerX = canvas.width / 2;
    const centerY = canvas.height / 2;
    const radius = 150;

    // 检查点击的节点
    graphData.nodes.forEach((node, index) => {
      const angle = (index / graphData.nodes.length) * 2 * Math.PI;
      const nodeX = centerX + Math.cos(angle) * radius;
      const nodeY = centerY + Math.sin(angle) * radius;

      const distance = Math.sqrt((x - nodeX) ** 2 + (y - nodeY) ** 2);
      if (distance <= node.size) {
        setSelectedNode(node);
      }
    });
  };

  const getNodeTypeIcon = (type: GraphNode['type']) => {
    switch (type) {
      case 'file': return '📄';
      case 'function': return '⚡';
      case 'class': return '🏗️';
      case 'variable': return '📦';
      default: return '❓';
    }
  };

  if (isLoading) {
    return (
      <div className={`flex-1 flex items-center justify-center ${className || ''}`}>
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500 mx-auto mb-4"></div>
          <p className="text-gray-600 dark:text-gray-400">加载代码图谱...</p>
        </div>
      </div>
    );
  }

  return (
    <div className={`flex-1 flex ${className || ''}`}>
      {/* 主图谱区域 */}
      <div className="flex-1 flex flex-col">
        {/* 工具栏 */}
        <div className="flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700">
          <div className="flex items-center space-x-4">
            <h1 className="text-xl font-bold text-gray-900 dark:text-white">
              代码图谱
            </h1>
            <div className="flex items-center space-x-2">
              <button
                className={`px-3 py-1 rounded text-sm ${
                  viewMode === 'overview'
                    ? 'bg-blue-500 text-white'
                    : 'bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-300'
                }`}
                onClick={() => setViewMode('overview')}
              >
                概览
              </button>
              <button
                className={`px-3 py-1 rounded text-sm ${
                  viewMode === 'detailed'
                    ? 'bg-blue-500 text-white'
                    : 'bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-300'
                }`}
                onClick={() => setViewMode('detailed')}
              >
                详细
              </button>
            </div>
          </div>
          
          <div className="flex items-center space-x-2">
            <button
              className="px-3 py-2 bg-blue-500 text-white rounded hover:bg-blue-600"
              onClick={loadGraphData}
            >
              刷新图谱
            </button>
          </div>
        </div>

        {/* 图谱画布 */}
        <div className="flex-1 bg-gray-50 dark:bg-gray-900 flex items-center justify-center">
          <canvas
            ref={canvasRef}
            width={800}
            height={600}
            className="border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 cursor-pointer"
            onClick={handleCanvasClick}
          />
        </div>
      </div>

      {/* 侧边栏 - 节点详情 */}
      <div className="w-80 border-l border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800">
        <div className="p-4">
          <h2 className="text-lg font-bold text-gray-900 dark:text-white mb-4">
            节点详情
          </h2>
          
          {selectedNode ? (
            <div className="space-y-4">
              <div className="flex items-center space-x-3">
                <span className="text-2xl">{getNodeTypeIcon(selectedNode.type)}</span>
                <div>
                  <h3 className="font-medium text-gray-900 dark:text-white">
                    {selectedNode.label}
                  </h3>
                  <p className="text-sm text-gray-500 dark:text-gray-400">
                    {selectedNode.type}
                  </p>
                </div>
              </div>
              
              <div className="space-y-2">
                <div className="flex justify-between">
                  <span className="text-sm text-gray-600 dark:text-gray-400">大小:</span>
                  <span className="text-sm text-gray-900 dark:text-white">{selectedNode.size}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-sm text-gray-600 dark:text-gray-400">颜色:</span>
                  <div 
                    className="w-4 h-4 rounded"
                    style={{ backgroundColor: selectedNode.color }}
                  ></div>
                </div>
              </div>

              {/* 连接信息 */}
              <div>
                <h4 className="font-medium text-gray-900 dark:text-white mb-2">连接</h4>
                <div className="space-y-1">
                  {graphData?.edges
                    .filter(edge => edge.source === selectedNode.id || edge.target === selectedNode.id)
                    .map(edge => (
                      <div key={edge.id} className="text-sm text-gray-600 dark:text-gray-400">
                        {edge.source === selectedNode.id ? '→' : '←'} {edge.type}
                      </div>
                    ))
                  }
                </div>
              </div>
            </div>
          ) : (
            <p className="text-gray-500 dark:text-gray-400">
              点击图谱中的节点查看详情
            </p>
          )}
        </div>
      </div>
    </div>
  );
};
